package cn.schedule.shiro;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import cn.schedule.util.User;

public class AuthenticationRealm extends AuthorizingRealm {

	/**
	 * 认证回调函数,登录时调用.
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		String userName = token.getUsername();
		String password = new String(token.getPassword());
		User user = new User();
		if (userName != null && !"".equals(userName)) {
			// 从数据库或 接口通过userName获取用户信息
			user.setLoginName("admin");
			//密码为admin（SHA1加密后）
			user.setPassword("d033e22ae348aeb5660fc2140aec35850c4da997");
			
			if (!user.getPassword().equals(password)) {
				throw new IncorrectCredentialsException();
			}
			return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
		} else {
			return null;
		}
	
	}

	/**
	 * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用.
	*/
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
	  /*MgtUser user = (MgtUser) principals.getPrimaryPrincipal();
		List<MgtAuthority> authList = userService.getAuthorityByUser(user.getUserId());
		List<MgtRule> ruleList = userService.getRulesByUser(user.getUserId());
		if (user != null) {
			SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
			for(MgtRule rule : ruleList){
				info.addRole(rule.getRuleId());
			}
			for(MgtAuthority auth : authList){
				info.addStringPermission(auth.getAuthorityCode());
			}
			return info;
		}*/
		return null;
	}
 
}
